package cn.edu.sjtu.se.dslab.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.sjtu.se.dslab.component.data.UploadFile;
import cn.edu.sjtu.se.dslab.service.IUploadFileService;

@Controller
@RequestMapping(value = "/upload_file")
public class UploadFileController {
	
	private final static String COMPONENT = "component";

	private final static String NAME = "name";

	private final static String TYPE = "type";

	private final static String URI = "uri";
	
	@Resource(name = "uploadFileService")
	IUploadFileService uploadFileService;

	@RequestMapping(value = "/get_by_name")
	@ResponseBody
	public Map<String, Object> getUploadFileListByName(
			@RequestParam(value = "name", required = false) String name) {
		if (name == null) {
			name = "";
		}
		System.out.println("name："+name);
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		List<UploadFile> files = uploadFileService.getUploadFilesByName(name);
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		if (files != null) {
			for (int i = 0; i < files.size(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put(URI, files.get(i).getUri());
				map.put(NAME, files.get(i).getName());
				map.put(TYPE, files.get(i).getType());
				map.put(COMPONENT, files.get(i).getComponent().getName());
				data.add(map);
			}
		}
		modelMap.put("data", data);
		modelMap.put("success", "true");
		return modelMap;

	}
	
	@RequestMapping(value = "/get_by_uri")
	@ResponseBody
	public Map<String, Object> getUploadFileListByUri(
			@RequestParam(value="uris[]", required=false) String[] uris) {
		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		if (uris == null) {
			modelMap.put("success", "false");
			return modelMap;
		}else{
			List<UploadFile> files = new ArrayList<UploadFile>();
			for (int i = 0; i < uris.length; i++) {
				UploadFile file = uploadFileService.getUploadFileByUri(uris[i]);
				if(file != null){
					files.add(file);
				}
				
			}
		
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		if (files != null) {
			for (int i = 0; i < files.size(); i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put(URI, files.get(i).getUri());
				map.put(NAME, files.get(i).getName());
				map.put(TYPE, files.get(i).getType());
				map.put(COMPONENT, files.get(i).getComponent().getName());
				data.add(map);
			}
		}
		modelMap.put("data", data);
		modelMap.put("success", "true");
		return modelMap;
		}
	}
}
